package com.bw.mallshop.dao;

import com.blankj.utilcode.util.LogUtils;
import com.bw.common.entity.BaseEntity;
import com.bw.mallshop.App;
import com.bw.mallshop.entity.UserEntityValues;

import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.MaybeObserver;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class UserSingle {

    private UserSingle(){}

    private volatile static UserSingle instance;

    public static UserSingle getInstance(){
        if (instance == null){
            synchronized (UserSingle.class){
                if (instance == null){
                    instance = new UserSingle();
                }
            }
        }
        return instance;
    }

    private UserObserver userObserver;

    public UserEntityValues userEntityValues;

    //是否登录
    public boolean isLogin(){
        if (userEntityValues == null)
            return false;
        return true;
    }

    //初始化查询
    public void init(App app){
        userObserver = new UserObserver();
        app.db.userDao().queryUserList().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userObserver);
    }

    //销毁
    public void destroy(){
        userObserver.destroy();
        userObserver = null;
    }
    //登录
    public void login(UserEntityValues userEntityValues){
        this.userEntityValues = userEntityValues;
    }
    //退出
    public void quit(){
        userEntityValues = null;
    }

    private static class UserObserver implements MaybeObserver<List<UserEntityValues>>{

        Disposable d;

        @Override
        public void onSubscribe(@NonNull Disposable d) {
            this.d = d;
        }

        @Override
        public void onSuccess(@NonNull List<UserEntityValues> userEntityValues) {
            if (userEntityValues == null)
                return;
            if (userEntityValues.size() == 0)
                return;
            UserSingle.getInstance().userEntityValues = userEntityValues.get(0);
        }

        @Override
        public void onError(@NonNull Throwable e) {
            LogUtils.e("获取本地用户数据失败");
        }

        @Override
        public void onComplete() {
            d.dispose();
        }

        public void destroy(){
            if (!d.isDisposed())
                d.dispose();
        }

    }

}
